package cn.zn.framework.activiti;

import cn.zn.framework.common.vo.FinanceValues;
import com.alibaba.fastjson.JSONObject;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.Map;

@Component
public class RestApi {
    public static final String TASK_QUERY_POST = "/query/tasks";
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private FinanceValues financeValues;

    public JSONObject queryTask(String json) {
        return this.queryForActiviti(RestApi.TASK_QUERY_POST, json);
    }

    /**
     * 调用activiti接口
     *
     * @param relUrl     接口路径
     * @param httpMethod 请求方式
     * @param params     参数（GET请求，路径必须包含参数?aa={aa}&bb={bb},将会替换对应的值）
     * @param json       使用body传递的值，将设置
     * @return
     */
    private JSONObject queryForActiviti(
            String relUrl,
            HttpMethod httpMethod,
            Map<String, Object> params,
            String json) {
        HttpHeaders httpHeaders = new HttpHeaders() {{
            String auth = "kermit:kermit";
            byte[] encodedAuth = Base64.encodeBase64(
                    auth.getBytes(Charset.forName("US-ASCII")));
            String authHeader = "Basic " + new String(encodedAuth);
            set("Authorization", authHeader);
        }};
        ResponseEntity<JSONObject> responseEntity = restTemplate.exchange
                (financeValues.getActiviti().getRestPath().concat(relUrl), httpMethod,
                        new HttpEntity<String>(httpHeaders),
                        JSONObject.class,
                        params);

        return responseEntity.getBody();
    }


    private JSONObject queryForActiviti(
            String relUrl,
            String json) {
        HttpHeaders httpHeaders = new HttpHeaders() {{
            String auth = "kermit:kermit";
            byte[] encodedAuth = Base64.encodeBase64(
                    auth.getBytes(Charset.forName("US-ASCII")));
            String authHeader = "Basic " + new String(encodedAuth);
            set("Authorization", authHeader);
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            setContentType(type);
        }};
        HttpEntity entity = new HttpEntity<>(json, httpHeaders);
        ResponseEntity<JSONObject> responseEntity = restTemplate.exchange
                (financeValues.getActiviti().getRestPath().concat(relUrl),
                        HttpMethod.POST,
                        entity,
                        JSONObject.class);
        return responseEntity.getBody();
    }
}
